<template>
  <view v-if="visible" class="toast-container">
	 <view :class="type === 2 ? 'another-container' : 'container'">
    <view class="toast">{{ message }}</view><input type="text" style="width: 200px;"></input>
	 <view class="modal-body">
	 	  <view v-if="type===3">
				<view class="input-box" >
				<span class="modal-text">实际重量</span><input  type="text" style="text-align: left;margin-left: 10px;" v-model="inputValue"/>
				</view>
				<view class="input-box" >
				<span class="modal-text">实际体积</span><input  type="text" style="text-align: left;margin-left: 10px;" v-model="periodValue"/>
				</view>
				<view class="input-box" >
				<span class="modal-text">提货件数</span><input  type="text"  style="text-align: left;margin-left: 10px;" v-model="textareaContent"/>
				</view>
			</view>
	 	  
			<view style="margin-top: 10px;" v-if="type===2">
				<view class="table" >
					<view>
						<view class="title" >品名</view>
						 <view class="con"  v-for="(item,index) in tableData" ><input style="background-color: #dddddd;"  type="text" v-model="item.description"></view>
					</view>
					<view>
						<view class="title">件数</view>
						 <view class="con"  v-for="(item,index) in tableData" ><input style="background-color: #ccc;" type="text" v-model="item.number"></view>
					</view>
					<view>
						<view class="title">重量</view>
						 <view class="con"  v-for="(item,index) in tableData" ><input style="background-color: #ccc;" type="text" v-model="item.weight"></view>
					</view>
					<view>
						<view class="title">体积</view>
						 <view class="con"  v-for="(item,index) in tableData"><input style="background-color: #ccc;" type="text" v-model="item.volume"></view>
					</view>
					<view>
						<view class="title">操作</view>
						 <view class="con"   v-for="(item,index) in tableData">
							<view style="width: 100%;"><u-button type="primary" size="mini" color="red" @click="deleteRow(index)" >删除</u-button></view>
						</view>
					</view>
				</view>
				<view style="text-align: center;" >
					 <view style="width: 100%;" v-if="enter===false" @click="addRow()"><u-button type="primary" icon="plus" color="#00dc33" size="mini"  shape="circle"></u-button></view>
					 <view style="width: 100%;" v-else @click="enterAdd()"><u-button type="primary"  color="#0072dc" size="mini"  shape="circle">确定</u-button></view>
				</view>
			</view>
		  <view class="photo-box" style="height: 70px;">
		   <span class="photo-text">照片</span>
		  		<view v-for="(image, index) in images" :key="index" class="image-item" >
		  		      <image :src="image" style="width: 80px; height: 80px;"></image>
		  		    </view>
		  	<span class="photo" v-if="images.length<2"><img src="../../../static/相机.png" class="photo-icon" @click="chooseImages">
		  	</span>
		  </view>
	 	  <view class="modal-footer">
	 	  		  <span @click="closeShow" class="quxiao" >取消</span><span class="yuyue" @click="addCilck">确定</span>
	 	  </view>
	 </view>
	<!-- <view class="modal-footer">
		<span @click="closeShow" class="quxiao" >取消</span><span class="yuyue" @click="addCilck">提货</span>
	</view> -->
  </view>
  </view>
</template>

<script>
		import {addTihuo,tihuo,duopm,addDpm,delDpm,updateNetwork} from '@/api/delivery.js';
		import {getDetails} from '@/api/appointment.js';
export default {
  data() {
    return {
      visible: false,
      message: '',
	  ids:[],
	  images: [] ,// 存储选中的图片路径,
	  items:{},
	  req:{},
	  picture:[],//存储后的路径
	  pictureString:'',
	  imageUrl:'',
	  textareValue:'',
	  inputValue:0,
	  periodValue:0,
	  textareaContent:0,
		tableData:[],
		enter:false
    };
  },
  props: {
  	 businessId: {
  		 type: Number,
  		 required: true
  	 },
	 type:{
		type: Number,
		required: true 
	 },
	 weight:{
	 		type: Number,
	 		required: true 
	 },
	 volume:{
	 		type: Number,
	 		required: true 
	 },
	 number:{
	 		type: Number,
	 		required: true 
	 }
      },
	watch: {
	    businessId(newVal, oldVal) {
	      // 当 someProp 更新时执行的逻
	      if(this.type===3){
			  getDetails({businessId: this.businessId}).then(res =>{
			  	this.items=res.data.data
			  	this.periodValue=this.items.volume
			  	this.inputValue=this.items.weight
			  	this.textareaContent=this.items.number
			  }).catch((error) => {
				  uni.showToast({
				      title: data,
				      icon: 'none'
				  });
			  });
		  }else{
				duopm({NetworkOrderId: this.businessId}).then(res=>{
					this.tableData=res.data.data
				}).catch((error) => {
				  uni.showToast({
				      title: data,
				      icon: 'none'
				  });
				 });
			this.periodValue=this.volume
			this.inputValue=this.weight
			this.textareaContent=this.number  
		  }
		 
	    },
		type(newVal, oldVal){
			console.log(this.businessId)
			if(this.type===2){
				this.periodValue=this.volume
				this.inputValue=this.weight
				this.textareaContent=this.number  
			}
		}
	  },
  methods: {
	enterAdd(index){
		const item = this.tableData[this.tableData.length - 1];
		console.log(item)
		if(item.description===''){
			uni.showToast({
			    title: '请填写品名',
			    icon: 'none'
			});
			return;
		}
		if(item.number===0){
			uni.showToast({
			    title: '件数不能为0',
			    icon: 'none'
			});
			return;
		}
		const form={
			networkOrderId:this.tableData[0].networkOrderId,
			description:item.description,
			number:item.number,
			weight:item.weight,
			volume:item.volume
		}
		addDpm(form).then(res=>{
			uni.showToast({
			    title: res.data.errorMessage,
			    icon: 'none'
			});
			this.getDpm()
			this.enter=false
		}).catch((error) => {
		  uni.showToast({
		      title: res.data.errorMessage,
		      icon: 'none'
		  });
		 });
	},
	addRow(){
		 // 检查最后一行是否填写完整
		 const lastRow = this.tableData[this.tableData.length - 1];
		 if (!this.isCurrentRowValid(lastRow)) {
		   uni.showToast({
		     title: "请填写完整当前行信息",
		     type: "none"
		   });
		   return; // 阻止添加新行
		 }
		this.tableData.push({
		  description: "", // 空品名
			number:	0,
		  weight: 0,     // 空重量
		  volume: 0      // 空体积
		});
		this.enter=true;
	},
	
	// 验证当前行是否填写完整
	  isCurrentRowValid(row) {
	    return row.description.trim() !== "" ;
	  },
		 // 删除行
		deleteRow(index) {
			const item=this.tableData[index]
			if(item.id===undefined){
				this.tableData.splice(index, 1);
				return;
			}
		  if (this.tableData.length > 1) {
		    delDpm({id:item.id}).then(res=>{
					uni.showToast({
							title: res.data.errorMessage,
							icon: 'none'
					});
					this.getDpm()
				}).catch((error) => {
					uni.showToast({
							title: res.data.errorMessage,
							icon: 'none'
					});
				});
		  } else {
		    uni.showToast({
		      title: "至少保留一行",
		      type: "none"
		    });
		  }
		},
		getDpm(){
			duopm({NetworkOrderId: this.businessId}).then(res=>{
					this.tableData=res.data.data
				}).catch((error) => {
				  uni.showToast({
				      title: data,
				      icon: 'none'
				  });
				 });
			this.periodValue=this.volume
			this.inputValue=this.weight
			this.textareaContent=this.number  
		},
	chooseImages() {
	      uni.chooseImage({
	        count: 9, // 允许选择图片的数量，默认为9
	        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图
	        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机
	        success: (res) => {
				 // 获取新选择的图片路径
				const newImages = res.tempFilePaths;
				this.images = this.images.concat(res.tempFilePaths);
				// 遍历新选择的图片，并检查是否已上传或已选择
				newImages.forEach((filePath) => {
	          // 将选中的图片路径添加到images
			    this.uploadFile(filePath);
			  });
	        },
			
	      });
		  
	    },
		uploadFile(filePath) {
		      uni.uploadFile({
		        url: 'https://image.ff5630.com/upload/buy/upload', // 仅为示例，非真实的接口地址
		        filePath: filePath,
		        name: 'file',
		        formData: {
		          user: 'test'
		        },
		        success: (uploadFileRes) => { // 使用箭头函数来保持this的上下文
				try {
				          // 解析服务器返回的JSON响应
				          const responseObj = JSON.parse(uploadFileRes.data);
				          const uploadedImageUrl = responseObj.data; // 假设服务器返回的是图片的URL
				 
				          // 检查并添加URL到picture数组（避免重复）
				          const completeUrl = uploadedImageUrl.startsWith('http://') || uploadedImageUrl.startsWith('https://')
				            ? uploadedImageUrl
				            : 'https://' + uploadedImageUrl; // 根据实际情况调整URL格式
				 
				          if (!this.picture.includes(completeUrl)) {
				            this.picture.push(completeUrl);
				          }
						  console.log(this.picture)
				          console.log('上传成功，图片URL：', completeUrl);
				 
				          // 其他处理上传成功后的逻辑可以在这里添加
				 
				        } catch (error) {
				          console.error('解析上传响应失败：', error);
				        }
		        },
		        fail(err) {
		          console.error('上传失败：', err);
		        }
		      });
			  },
	show(msg) {
	  this.message = msg;
	  this.visible = true;
	},
	addCilck(){
		this.req.tihuoWeight=this.inputValue
		this.req.tihuoVolum=this.periodValue
		this.req.tihuoNumber=this.textareaContent
		this.req.tihuoImage=this.picture.toString();
		console.log(this.businessId)
		this.req.ids=[]
		this.req.ids.push(this.businessId);
		this.req.id=this.businessId
		this.ids=[]
		this.ids.push(this.businessId);
		console.log(this.req)
		if(this.type==3){
			 addTihuo(this.ids).then(res =>{
			 	this.visible = false;
				this.$emit('add-item', 1);
			 uni.showToast({
			 	        title: res.data.errorMessage,
			 	        icon: 'success',
			 	    });
			 }).catch((error) => {
			     // 请求失败
			     console.error('提货失败', error);
			     uni.showToast({
			         title: '提货失败，请重试',
			         icon: 'none',
			     });
			 });
			this.visible = false;
		}else{
			this.addDetail();
			tihuo(this.req).then(res =>{
			 	this.visible = false;
				this.$emit('add-item', 1);
			 uni.showToast({
			 	        title: res.data.errorMessage,
			 	        icon: 'success',
			 	    });
			 }).catch((error) => {
			     // 请求失败
			     console.error('提货失败', error);
			     uni.showToast({
			         title: '提货失败，请重试',
			         icon: 'none',
			     });
			 });
			this.visible = false;
		}
		
	},
	addDetail(){
		updateNetwork(this.tableData).then(res =>{
			if(res.data.code!==20000){
				uni.showToast({
				    title: '提货失败，请重试',
				    icon: 'none',
				});
				return;
			}
		}).catch((error) => {
		    // 请求失败
		    console.error('提货失败', error);
		    uni.showToast({
		        title: '提货失败，请重试',
		        icon: 'none',
		    });
		});
	},
	closeShow(){
		this.visible = false;
	}
  }
};
</script>

<style scoped lang="scss">
	.photo-box{
		margin-top: 20px;
		display: flex;
		align-items: center;
		border-radius: 4px;
		padding: 10px;
		text-align: center;
		box-sizing: border-box;
		flex: 1;
		height: 50px;
		margin-top: 10px;
		border: none;
		outline: none;
	}
	.photo-icon{
		margin-left: 2px;
		margin-top: 14px;
		width: 40px;
		height: 40px;
	}
	.photo{
		margin-left: 30px;
		width: 70px;
		height: 70px;
		display: inline-block;
		border: 1.5px dashed #ccc;
	}
	.image-item{
		display: inline-block;
		margin-left: 20px;
		margin-top: 30px;
	}
	.photo-text{
		margin-left: 10px;
		margin-right: 5px;
		color: black;
		font-size: 14px;
	}
.input-box {
  display: flex;
  align-items: center;
  background-color: #ebebeb;
  border-radius: 4px;
  padding: 10px;
  text-align: center;
  box-sizing: border-box;
  flex: 1;
  height: 50px;
  margin-top: 10px;
  border: none;
  outline: none;
}
.modal-text{
	font-size: 14px;
	margin-left: 10px;
	text-align: left;
	line-height: 30px;
	color: #ccc;
}
.modal-body {
}
.toast-container {
  position: fixed;
	top: 0%;
	left: 0%;
  z-index: 9999;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5); /* 半透明黑色背景 */
  
}
.another-container{
	position: fixed;
	top: 50%;
	left: 50%;
	width: 300px;
	transform: translate(-50%, -50%);
	justify-content: center;
	align-items: center;
	background-color: #fff;
	color: black;
	text-align: center;
	border-radius: 5px;
	padding: 10px 20px;
}
.container{
	position: fixed;
	top: 50%;
	left: 50%;
	width: 300px;
	height: 40%;
	transform: translate(-50%, -50%);
	justify-content: center;
	align-items: center;
	background-color: #fff;
	color: black;
	text-align: center;
	border-radius: 5px;
	padding: 10px 20px;
}

.toast {
  font-size: 16px;
  font-weight: bold;
  position: relative;
  top: 20px;
}
.modal-footer {
  display: flex;
  justify-content: space-around;
  // position: relative;
  // top: 32px;
  border-top: 1px solid #ccc;
}
.yuyue{
	color: #ffaa00;
	font-weight: bold;
	border-left: 1px solid #ccc;
	display: inline-block;
	height: 38px;
	line-height: 40px;
	width: 150px;
	font-size: 15px;
	position: relative;
	left: 30px;
}
.quxiao{
	text-align: center;
	margin-top: 10px;
	margin-left: 30px;
	font-size: 15px;
}
.table{
	width: 100%;
	overflow-x: auto;
	background: #fff;
	display: flex;
	flex-direction: row;
	.title {
			padding: 5px 5px;
			text-align: center;
			font-size: 26upx;
			background: #1a6eea;
			color: #fff;
		}
		.con {
			text-align: center;
			font-size: 24upx;
			padding: 8px 10px;
		}
		.status{
			color: #1a6eea;
		}
}

</style>